/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aufgabe1;

import java.util.LinkedList;

/**
 *
 * @author benjamin
 */
public class BackPack<T extends Item> {
    private String _name;
    private final int _size;
    private int _freeSpace;
    private int _contentValue;
    private LinkedList<T> _items;
    
    /**
     * Constructor
     * 
     * @param name - name of backpack
     * @param size - max size
     */
    public BackPack(String name, int size) {
        _name = name;
        _size = size;
        _freeSpace = size;
        _contentValue = 0;
        _items = new LinkedList<T>();
    }
    
    
    /**
     * pack - add a new item to backpack
     * 
     * @param item - to add
     * @return - true if its enough space, otherwise false
     */
    public boolean pack(T item) {
        if (_freeSpace >= item.getSize()) {
            _items.addFirst(item);
            _freeSpace -= item.getSize();
            _contentValue += item.getValue();
            return true;
        }
        return false;
    }
    
    
    /**
     * unpack - return the least (most top) item
     * 
     * @return
     * @throws BackPackException 
     */
    public T unpack() throws BackPackException {
        if (isEmpty()) {
            throw new BackPackException("Backpack is already empty");
        }
        T rv = _items.removeFirst();
        _freeSpace += rv.getSize();
        _contentValue -= rv.getValue();
        return rv;
    }
    
    
    /**
     * Returns true if backpack is empty
     * @return 
     */
    public boolean isEmpty() {
        return _items.isEmpty();
    }
    
    
    /**
     * Returns backpack's free space
     * @return 
     */
    public int freeSpace() {
        return _freeSpace;
    }
    
    
    /**
     * Return's backpack's content value
     * @return 
     */
    public int contentValue() {
        return _contentValue;
    }
    
    
    @Override
    public String toString() {
        StringBuilder rv = new StringBuilder();
        rv.append("BackPack - Name: ");
        rv.append(_name);
        rv.append(", Size: ");
        rv.append(_size - _freeSpace);
        rv.append("/");
        rv.append(_size);
        rv.append(", Items: ");
        rv.append(_items.size());
        rv.append(", Content-Value: ");
        rv.append(_contentValue);
        return rv.toString();
    }
    
    @Override
    protected BackPack<T> clone() {
        BackPack<T> rv = new BackPack<T>(_name, _size);
        rv._freeSpace = _freeSpace;
        rv._contentValue = _contentValue;
        rv._items = new LinkedList<T>(_items);
        return rv;
    }

}
